package servlet;

import bean.Rank;
import utils.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String sql = "select * from rank";
        ResultSet rs = DBUtil.query(sql);
        ArrayList<Rank> list = new ArrayList<>();
        try {
            while (rs.next()) {
                int rankId = rs.getInt("rank_id");
                String type = rs.getString("type");
                list.add(new Rank(rankId,type));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        request.setAttribute("list",list);
        request.getRequestDispatcher("/WEB-INF/add.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String sql = "insert into info values (?,?,?,?,?)";
        String address = request.getParameter("address");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        int rankId = Integer.parseInt(request.getParameter("rankId"));
        int rs = DBUtil.update(sql,null,name,age,address,rankId);
        if (rs > 0) {
            response.sendRedirect("/list");
        }
    }
}
